package com.heima.behavior.service.impl;


import com.heima.behavior.dtos.CollectionBehaviorDto;
import com.heima.behavior.pojos.ApCollectionBehavior;
import com.heima.behavior.pojos.ApLikesBehavior;
import com.heima.behavior.service.ApCollectionBehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApCollectionBehaviorServiceImpl implements ApCollectionBehaviorService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ResponseResult Collection(CollectionBehaviorDto dto) {
        //1.检验参数
        if(dto.getEntryId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.获取登录人的信息
        ApUser user = AppThreadUtil.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }


        String collection_hash_key="USER_COLLECTION_"+dto.getEntryId();
        Boolean hasKey = redisTemplate.opsForHash().hasKey(collection_hash_key, user.getId() + "");

        if(!hasKey && dto.getOperation()==0){
            redisTemplate.opsForHash().put(collection_hash_key,user.getId()+"","1");

            ApCollectionBehavior apCollectionBehavior=new ApCollectionBehavior();
            apCollectionBehavior.setUserId(user.getId().longValue());
            apCollectionBehavior.setType(dto.getType());
            apCollectionBehavior.setCollectionTime(new Date());
            apCollectionBehavior.setArticleId(dto.getEntryId());
            mongoTemplate.insert(apCollectionBehavior);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        if(hasKey && dto.getOperation()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.COLLECTION_USER_SUCCESS);
        }
        if(hasKey && dto.getOperation()==1){
            redisTemplate.opsForHash().delete(collection_hash_key,user.getId()+"");
            Query query=Query.query(Criteria.where("userId").is(user.getId()).and("articleId").is(dto.getEntryId()));
            mongoTemplate.remove(query, ApCollectionBehavior.class);
            return ResponseResult.okResult(AppHttpCodeEnum.COLLECTION_CANCEL_SUCCESS);
        }

        return null;
    }
}
